<template>
  <div class="app-container">
    <el-button v-waves type="primary" @click="handleAddRole">创建角色</el-button>

    <el-table
      :data="table.rolesList"
      row-key = "roleId"
      v-loading="table.listLoading"
      style="width: 100%;margin-top:30px;"
      border
    >
    <el-table-column align="center" label="角色名称" width="220">
      <template slot-scope="scope">
        {{ scope.row.roleName }}
      </template>
    </el-table-column>
      <el-table-column align="center" label="角色标识" width="220">
        <template slot-scope="scope">
          {{ scope.row.roleKey }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="角色说明">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column align="center" >
        <template slot-scope="scope">
          <el-button v-waves type="primary" size="small" @click="handleEdit(scope)">Edit</el-button>
          <el-button v-waves type="danger" size="small" @click="handleDelete(scope)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="table.total > 0" :total="table.total" :page.sync="table.listQuery.page" :pageSizes.sync="table.pageSizes"  :limit.sync="table.listQuery.limit" @pagination="getRoles" />

    <el-dialog :visible.sync="dialog.visible" :title="dialog.title">
      <el-form :model="role" label-width="80px" label-position="left" style="margin: 0px 20px 0px 20px">
        <el-form-item label="角色名称">
          <el-input v-model="role.roleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="角色标识">
          <el-input v-model="role.roleKey" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="角色说明">
          <el-input
            v-model="role.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="角色说明"
          />
        </el-form-item>
        <el-form-item label="权限分配">
          <el-tree
            ref="tree"
            :check-strictly="tree.checkStrictly"
            :data="tree.data"
            :props="tree.props"
            show-checkbox
            node-key="key"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialog.visible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import { deepClone } from '@/utils'
import { getPermissionTree, getRoles, getRole, addRole, deleteRole, updateRole } from '@/api/role'
const defaultRole = {
  roleId: '',
  roleKey: '',
  roleName: '',
  description: '',
  permissions: []
}

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      table : {
        total: 0,
        rolesList: [],
        listLoading: true,
        pageSizes: [10, 20, 30 ,50 , 100],
        listQuery: {
          page: 1,
          limit: 10,
          sort: ''
        }
      },
      dialog: {
        visible: false,
        title: '',
        addTitle: '添加角色',
        editTitle: '编辑角色',
        type: '',
        addType: 'add',
        editType: 'edit'
      },
      tree: {
        data: [],
        checkStrictly: false,
        props: {
          label: 'name',
          children: 'children',
        }
      },
      role: Object.assign({}, defaultRole)
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    try {
      Promise.all([this.getRoles(), this.getPermissionTree()])
    } catch (e) {
      console.log(e)
    }
  },
  methods: {
    async getPermissionTree(){
      const res = await getPermissionTree()
      this.tree.data = res.map( (item, index, array) => {
        item.key = item.managementId;
        if (item.nodes) {
          item.nodes.forEach( ( item , index ) => {
            item.key = item.resourceId
            item.name = item.resourceName
          })
          item.children.push(...item.nodes)
        }
        return item
      })
    },
    async getRoles() {
      this.$set(this.table,'listLoading',true)
      //sync
      const res = await getRoles(this.table.listQuery)
      this.$set(this.table,'total',parseInt(res.total))
      this.$set(this.table,'rolesList',res.result)
      this.$set(this.table,'listLoading',false)
    },
    handleAddRole() {
      //clear tree
      if (this.$refs.tree) {
       this.$refs.tree.setCheckedNodes([])
      }
      this.role = deepClone(defaultRole)
      this.dialog.type = this.dialog.addType
      this.dialog.title = this.dialog.addTitle
      //open dialog
      this.dialog.visible = true
    },
    async handleEdit(scope) {
      this.dialog.type = this.dialog.editType
      this.dialog.title = this.dialog.editTitle
      //open dialog
      this.dialog.visible = true
      this.checkStrictly = true
      //get RoleId
      const roleId = scope.row.roleId;
      //sync getRole
      this.role = await getRole ( roleId )
      //docment mount
      this.$nextTick(() => {
        this.role.permissions.forEach( ( item ,index ) => {
          this.$refs.tree.setChecked(item.resourceId, true)
        })
        this.checkStrictly = false
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('是否确定删除该角色', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteRole(row.roleId)
          this.table.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
        .catch(err => { console.error(err) })
    },
    async confirmRole() {
      const checkedNodes = this.$refs.tree.getCheckedNodes()
      //clear array
      this.role.permissions = []
      checkedNodes.forEach( ( item, index) => {
        if(item.nodeType !== 'management'){
          console.log(item.permission)
          this.role.permissions.push({
            'resourceId' : item.resourceId,
            'permission' : item.permission
          })
       }
      })
      let notifyTitle = ''
      if(this.dialog.type === this.dialog.addType){
        notifyTitle = '添加成功'
        await addRole(this.role)
      }
      if(this.dialog.type === this.dialog.editType){
        notifyTitle = '修改成功'
        await updateRole(this.role)
      }
      //notify
      const { description, roleName } = this.role
      let notify = {
        title: `${notifyTitle}`,
        type: 'success',
        dangerouslyUseHTMLString: true,
        message: `<div>角色名称: ${roleName}</div> <div>说明: ${description}</div>`
      }
      this.$notify(notify)
      //close dialog
      this.dialog.visible = false
      //reload table
      await this.getRoles()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
